package com.kaili.controller.common.v1;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.plugins.Page;
import com.kaili.client.service.ILoginUserInfoService;
import com.kaili.common.exception.BaseExcept;
import com.kaili.common.tenant.DbContextHolder;
import com.kaili.common.util.*;
import com.kaili.db.service.IHsBasicSeqService;
import com.kaili.db.service.IHsEwbsStowageService;
import com.kaili.db.service.IHsOptEwbAppointService;
import com.kaili.db.service.IHsOptEwbService;
import com.kaili.except.ResponseStatus;
import com.kaili.feign.UserFeignClient;
import com.kaili.pojo.dto.ewb.EwbAddDTO;
import com.kaili.pojo.dto.ewb.EwbQueryAppointsDTO;
import com.kaili.pojo.dto.ewb.EwbQueryDTO;
import com.kaili.pojo.entity.HsOptEwb;
import com.kaili.pojo.vo.AppointQueryVO;
import com.kaili.pojo.vo.CustomerVO;
import com.kaili.pojo.vo.EwbQueryVO;
import com.kaili.pojo.vo.EwbSummaryVO;
import com.kaili.utils.DateUtils;
import com.kaili.version.ApiVersion;
import freemarker.template.Configuration;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.commons.beanutils.BeanMap;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.MessageSource;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.*;

@ApiVersion(1)
@RequestMapping("/{api_version}")
@RestController("ewbControllerC")
@Api(tags = "[PDA和WEB端通用]托运开单服务", description = "[通用]托运开单相关API")
public class EwbController {
    private Logger logger = LoggerFactory.getLogger(getClass());

    @Autowired
    IHsOptEwbAppointService ewbAppointService;

    @Autowired
    ILoginUserInfoService loginUserInfoService;

    @GetMapping("/c/ewbs/appoints/unBillings")
    @ApiOperation(value = "查询未开单的预约登记列表")
    public Page<AppointQueryVO> queryUnBillingAppointList(@ModelAttribute EwbQueryAppointsDTO req) throws BaseExcept {
        if(req.getCur()!=null&&req.getPageSize()!=null) {
            Page<AppointQueryVO> pager = new Page<AppointQueryVO>(req.getCur(), req.getPageSize());
            Map<Object,Object> map=new HashMap<>();
            map.putAll(new BeanMap(req));
            map.put("isBilling", 0);
            map.put("siteId", loginUserInfoService.getLoginSiteId());
            pager = ewbAppointService.queryUnBillingAppointPageList(pager,map);
            return  pager;
        }
        throw new BaseExcept(ResponseStatus.UNBILLING_APPOINT_QUERY_ERR);
    }

    //查询当前登陆公司的最大货量
    public static Double maxWeight(IHsOptEwbService ewbService){
        String currentDbType = DbContextHolder.getDbType();
        DbContextHolder.setDbType(CommonConstant.MAIN_DB_READ);
        Double maxWeight=ewbService.selectMaxVolume(LoginDetailUtils.getCompanyCode());
        DbContextHolder.setDbType(currentDbType);
        return  maxWeight;
    }

    public static ResponseStatus check(IHsOptEwbService ewbService,IHsEwbsStowageService stowageService,EwbAddDTO addBean){
        if(!CommonRegexUtil.isRegexMoney(addBean.getTotalAmount())
                ||!CommonRegexUtil.isRegexMoney(addBean.getSendCharge())
                ||!CommonRegexUtil.isRegexMoney(addBean.getTotalFreightCharge())
                ||!CommonRegexUtil.isRegexWeight(addBean.getTotalWeight())
                ||!CommonRegexUtil.isRegexVal(addBean.getTotalVol())){
            return ResponseStatus.EWB_ADD_ERR;
        }


        boolean isAdd = false;
        String operationId = addBean.getOperationId();
        if(operationId == null){
            isAdd = true;
        }

        //查询当前登陆公司的最大货量(查出来为吨 需要转换为千克)
        Double maxWeight=maxWeight(ewbService);
        //查询当天已使用货量
        Double useWeight = 0d;
        HsOptEwb optEwb = ewbService.getEWbByEwbNo(addBean.getEwbNo());
        if(isAdd){
            useWeight=ewbService.selecthighVolume(addBean.getEwbNo(), DateUtils.getCurrentDate());
        }else{
            useWeight=ewbService.selecthighVolume(addBean.getEwbNo(), optEwb.getCreatedTime());
        }
        if(maxWeight!=null&&useWeight!=null){
            if((useWeight+addBean.getTotalWeight().doubleValue())>(maxWeight*1000)){
                return ResponseStatus.USE_WEIGHT;
            }
        }

        if(isAdd && ewbService.isEwbNoRepeat(addBean.getEwbNo())) {
            return ResponseStatus.EWB_ADD_DUPLICATE;
        }else if(!isAdd && !ewbService.isEwbNoRepeat(addBean.getEwbNo())){
            return ResponseStatus.EWB_NOT_EXISTS;
        }

        if(!isAdd && stowageService.isStowage(addBean.getEwbNo())){
            return ResponseStatus.EWB_NOT_UPDATE;
        }

        return ResponseStatus.RESPONSE_OK;
    }
}